<template>
  <div v-if="flag" :class="{'mobile-container': showMobilePage}">
    <!-- 只选择一级部门 -->
    <selectWithoutHttp
      v-if="!element.options.selectChild"
      v-model="computedValue"
      :list-data="deptOption"
      :collapse-tags="false"
      :disabled="element.options.disabled && !isInDetail"
      :multiple="element.options.multiple"
      :placeholder="element.options.placeholder || '请选择'"
      key-name="id"
      value-type="object"
      clearable
      class="width240"
      filterable
    />
    <!-- 可选择子部门 -->
    <SelectDept
      v-else
      ref="selectDeptRef"
      v-model="computedValue"
      :disabled="element.options.disabled && !isInDetail"
      :multiple="element.options.multiple"
      :retrun-array="true"
      :placeholder="element.options.placeholder || '请选择'"
      label-name="name"
      key-name="id"
      class="width240" />
    <el-checkbox v-if="isCanIncludeSubDept" v-model="isIncludeSubDeptVal" style="margin-top: 3px;">包含子部门</el-checkbox>
  </div>
</template>

<script>
import { deptList } from '@/api/select';
import { mapState } from 'vuex';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import SelectDept from './selectDept';
export default {
  components: { SelectDept, selectWithoutHttp },
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  props: {
    value: {
      type: Object | Array | String | Number,
      default: null
    },
    element: {
      type: Object,
      default: () => ({})
    },
    isPreView: { // 是否配置中
      type: Boolean,
      default: false
    },
    isInDetail: { // 是否详情页展示，isDetail可能因为事件而改变，导致实际在详情页而 isDetail 为false，这个属性不会改变，详情页永远为true
      type: Boolean,
      default: false
    },
    isCanIncludeSubDept: {
      type: Boolean,
      default: false
    },
    isIncludeSubDept: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      deptOption: [],
      deptTreeList: [],
      flag: true
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage,
      'initDeptList': state => state.user.deptList
    }),
    isIncludeSubDeptVal: {
      get() {
        return this.isIncludeSubDept;
      },
      set(val) {
        this.$emit('isSubDeptChange', val);
      }
    },
    computedValue: {
      get() {
        const selectChild = this.element.options.selectChild;
        if (!selectChild) {
          return this.value || '';
        } else {
          const multiple = this.element.options.multiple;
          if (!multiple) {
            return this.value ? this.value.id : '';
          } else {
            if (!this.value) return [];
            return this.value.map(i => i.id);
          }
        }
      },
      set(val) {
        const selectChild = this.element.options.selectChild;
        if (!selectChild) {
          this.$emit('changeValue', val);
        } else {
          this.setValue(val);
        }
      }
    }
  },
  watch: {
    'element.options.selectChild': {
      handler(val) {
        const multiple = this.element.options.multiple;
        this.initValue(multiple);
      },
      deep: true
    },
    'element.options.multiple': {
      handler(val) {
        this.initValue(val);
      },
      deep: true
    }
  },
  created() {
    if (this.initDeptList && this.initDeptList.length) {
      this.deptOption = this.initDeptList;
    } else {
      this.getDeptList(true);
    }
  },
  methods: {
    initValue(multiple) {
      if (!this.isPreView) return;
      let value = this.element.value || '';
      value = !Array.isArray(value) ? value : value[0];
      this.$set(this.element, 'value', multiple ? value ? [value] : [] : value);
      // this.$set(this.element.options, 'defaultValue', '');
      this.flag = false;
      this.$nextTick(() => {
        this.flag = true;
      });
    },
    handleSubDeptInclude(e) {
      this.$emit('isSubDeptChange', e);
    },
    async getDeptList(init) {
      const res = await deptList();
      res.data.forEach(i => {
        i.name = i.value;
      });
      this.deptOption = res.data;
      if (init) this.$store.commit('SET_DEPTLIST', res.data);
    },
    getName(id) {
      const selectChild = this.element.options.selectChild;
      if (!selectChild) {
        const item = this.deptOption.find(i => i.id === id);
        return item ? item.value : '';
      }
    },
    setValue(val) {
      const multiple = this.element.options.multiple;
      let node = this.$refs.selectDeptRef.getCheckedNodes();
      const value = Array.isArray(val) ? val : [val];
      if (val && value.length && node && node.length) {
        node = node.filter(i => value.includes(i.data.id));
        const ans = [];
        // eslint-disable-next-line no-inner-declarations
        function getValue(data) {
          data.forEach(i => {
            if (value.includes(i.data.id)) {
              if (!ans.find(j => j.id === i.data.id)) { // 勾选去重
                ans.push({ id: i.data.id, name: i.data.name });
              }
            }
            if (i.children) {
              getValue(i.children);
            }
          });
        }
        getValue(node);
        this.$emit('changeValue', multiple ? ans : ans[0]);
      } else {
        this.$emit('changeValue', multiple ? [] : '');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.width240 {
  width: 100%;
  &::v-deep {
    .el-select {
      width: 100%;
    }
    .el-input__inner {
      width: 100%;
    }
  }
}
.mobile-container {
  &::v-deep {
    .el-input__inner {
      width: 100% !important;
    }
  }
}
</style>
